package com.duolaibei.business.view.goods;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.view.goods.mode.TypesBean;
import com.duolaibei.business.view.goods.mode.TypesBeanManager;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by Administrator on 2018/9/28.
 */

public class TypesManegeActiviy extends BaseActivity {

    @Inject(R.id.back)
    private RelativeLayout mBack;
    @Inject(R.id.title)
    private TextView mTitle;
    @Inject(R.id.btn_types_edit)
    private TextView mTxtTypesEdit;
    @Inject(R.id.recycle_types)
    private RecyclerView mRecycleTypes;
    @Inject(R.id.btn_types_add)
    private TextView mTxtTypeAdd;

    private TypesAdapter mTypesAdapter;

    private List<TypesBean> mTypesList = new ArrayList<>();

    private String class_sign = "";

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_types_manage);
    }

    @Override
    protected void initViews() {
        mTitle.setText("分类管理");
    }

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        if (intent.getExtras() != null) {
            class_sign = intent.getStringExtra("class_sign");
        }
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setTypesAdapter();
        initTypesData();
    }

    @Override
    protected void onSetListener() {
        mBack.setOnClickListener(getThis());
        mTxtTypesEdit.setOnClickListener(getThis());
        mTxtTypeAdd.setOnClickListener(getThis());
        mTypesAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (!CommonUtil.isEmpty(class_sign)) {
                    Intent intent = new Intent();
                    intent.putExtra("goods_type", mTypesList.get(position).getName());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            finish();
        } else if (v.getId() == R.id.btn_types_edit) {
            editType();
        } else if (v.getId() == R.id.btn_types_add) {
            addType();
        }
    }

    private void initTypesData() {
        List list = TypesBeanManager.getInstance().selectAllTypes();
        mTypesList.clear();
        mTypesList.addAll(list);
        mTypesAdapter.notifyDataSetChanged();
    }

    private void setTypesAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getThis());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycleTypes.setLayoutManager(layoutManager);
        Drawable drawable = ContextCompat.getDrawable(Objects.requireNonNull(getThis()), R.drawable.shape_recycle_div);
        DividerItemDecoration decoration = new DividerItemDecoration(Objects.requireNonNull(getThis()), DividerItemDecoration.VERTICAL);
        if (drawable != null) {
            decoration.setDrawable(drawable);
            mRecycleTypes.addItemDecoration(decoration);
        } else
            mRecycleTypes.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getThis()), DividerItemDecoration.VERTICAL));
        mTypesAdapter = new TypesAdapter(getThis(), R.layout.item_types_manage, mTypesList);
        mRecycleTypes.setAdapter(mTypesAdapter);
    }

    private class TypesAdapter extends CommonAdapter<TypesBean> {

        public TypesAdapter(Context context, int layoutId, List<TypesBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final TypesBean typesBean, int position) {
            holder.setText(R.id.type_name, typesBean.getName());
            boolean isShow = typesBean.getIsShowEdit();
            if (!isShow) {
                holder.getView(R.id.ic_delete_category).setVisibility(View.GONE);
                holder.getView(R.id.ic_edit_category).setVisibility(View.GONE);
            } else {
                holder.getView(R.id.ic_delete_category).setVisibility(View.VISIBLE);
                holder.getView(R.id.ic_edit_category).setVisibility(View.VISIBLE);
            }
            //删除
            holder.getView(R.id.ic_delete_category).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteType(typesBean);
                }
            });
            //编辑
            holder.getView(R.id.ic_edit_category).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editTypeName(typesBean);
                }
            });
        }
    }

    /**
     * 编辑类型按钮
     */
    private void editType() {
        //遍历类型名称集合
        for (TypesBean typesBean : mTypesList) {
            typesBean.setIsShowEdit(true);
        }
        mTypesAdapter.notifyDataSetChanged();
        mTxtTypeAdd.setVisibility(View.GONE);
        mTxtTypesEdit.setText("取消");
        mTxtTypesEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //遍历类型名称集合
                for (TypesBean typesBean : mTypesList) {
                    typesBean.setIsShowEdit(false);
                }
                mTypesAdapter.notifyDataSetChanged();
                mTxtTypeAdd.setVisibility(View.VISIBLE);
                mTxtTypesEdit.setText("编辑");
                mTxtTypesEdit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        editType();
                    }
                });
            }
        });
    }

    /**
     * 增加新的类型
     */
    @SuppressLint("RestrictedApi")
    private void addType() {
        //判断类型是否重复
        AlertDialog.Builder builder = new AlertDialog.Builder(getThis());
        builder.setTitle("新增分类");
        final EditText editText = new EditText(getThis());
        editText.setTextSize(15);
        editText.setHint("请输入分类名称");
        builder.setView(editText, 60, 40, 60, 40);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                TypesBean typesBean = new TypesBean();
                String content = editText.getText().toString();
                typesBean.setName(content);
                typesBean.setIsShowEdit(false);
                typesBean.setIsChoosed(false);
                typesBean.setTypeNum(Integer.parseInt(getRadomInt()));
                if (isRepeatType(typesBean)) {
                    return;
                }
                TypesBeanManager.getInstance().addType(typesBean);
                initTypesData();
            }
        });
        builder.show();
    }

    /**
     * 删除类型
     */
    private void deleteType(final TypesBean typesBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getThis());
        builder.setTitle("提示");
        builder.setMessage("确定删除" + typesBean.getName() + "分类吗？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                TypesBeanManager.getInstance().deleteTypes(typesBean);
                initTypesData();
                editType();
            }
        });
        builder.show();
        //查找该类型是否有商品
    }

    /**
     * 编辑类型名称
     */
    @SuppressLint("RestrictedApi")
    private void editTypeName(final TypesBean typesBean) {
        //判断类型是否重复
        AlertDialog.Builder builder = new AlertDialog.Builder(getThis());
        builder.setTitle("修改分类名称");
        final EditText editText = new EditText(getThis());
        editText.setTextSize(15);
        editText.setText(typesBean.getName());
        editText.setSelection(typesBean.getName().length());
        builder.setView(editText, 60, 40, 60, 40);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newName = editText.getText().toString();
                if (CommonUtil.isEmpty(newName)) {
                    showToast("分类不能为空");
                    return;
                }
                typesBean.setName(newName);
                typesBean.setIsShowEdit(false);
                if (isRepeatType(typesBean)) {
                    return;
                }
                TypesBeanManager.getInstance().updateTypes(typesBean);
                initTypesData();
                editType();
            }
        });
        builder.show();
    }

    private boolean isRepeatType(TypesBean typesBean) {
        List<TypesBean> list = TypesBeanManager.getInstance().selectAllTypes();
        for (TypesBean typesBean1 : list) {
            if (typesBean1.getName().endsWith(typesBean.getName())) {
                showToast("名称不能重复");
                return true;
            }
        }
        return false;
    }

    /**
     * 获取五位数随机数
     *
     * @return
     */
    private String getRadomInt() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            int a = (int) (Math.random() * 9) + 1;
            buffer.append(String.valueOf(a));
        }
        return buffer.toString();
    }

    public interface ItemTouchHelperAdapter {
        //数据交换
        void onItemMove(int fromPosition, int toPosition);

        //数据删除
        void onItemDissmiss(int position);
    }

}
